#!usr/bin/python
# -*- coding:utf-8 -*-
import requests
import json
import sys
import ssl
import urllib2

reload(sys)
sys.setdefaultencoding('utf8')

if hasattr(ssl,'_create_unverified_context'):
    context = ssl._create_unverified_context()


class WeChat(object):
    access_token = ''

    def __init__(self, appid, appSecret):
        self.appid = appid
        self.appSecret = appSecret

    def get_access_token(self):
        if (self.appid == "" or self.appSecret == ""):
            print "appid or appSecret is none"
            return

        url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s' % (
            self.appid, self.appSecret)
        # ret = requests.get(url)
        ret = urllib2.urlopen(url).read()
        obj = json.loads(ret)
        self.access_token = obj["access_token"]
        print self.access_token

    def send_message(self, openId, content):
        if (self.access_token == ""):
            print "access token is none"
            self.get_access_token()

        json_str = {'touser': openId, 'msgtype': 'text', 'text': {'content': content}}
        msg = json.dumps(json_str, ensure_ascii=False)
        print msg
        url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=%s" % self.access_token
        ret = urllib2.urlopen(url, data=msg).read()
        # ret = requests.post(url, data=msg)
        # if ret.status_code == 200:
        print ret


if __name__ == "__main__":
    appId = "wx21bd4b86851af6c7";
    appSecret = "872e068c17a7d143b226d1c8497b3c22";
    wt = WeChat(appId, appSecret)
    # 用户标识openid
    openid = "oKf90s7PLpzfnr1TFfxr9KVDoG8c"
    wt.send_message(openid, '啊啊啊')

    # milo oKf90sx-I4sMiAIqWrZwqdngREdQ
    # marco oKf90s7PLpzfnr1TFfxr9KVDoG8c
    # lu oKf90s-eBCGhDkJNDNcx9EIHu6z8
